﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Jayden.Dll.Core.IO
{
	public class BigEndianReader : IDisposable
	{
		private BinaryReader m_Reader;
		private bool m_DisposeInnerReader;

		public BigEndianReader(Stream stream)
		{
			m_Reader = new BinaryReader(stream);
			m_DisposeInnerReader = true;
		}

		public BigEndianReader(BinaryReader writer)
		{
			m_Reader = writer;
			m_DisposeInnerReader = false;
		}

		public BinaryReader InnerReader { get { return m_Reader; } }

		public short ReadInt16()
		{
			return BitConverter.ToInt16(ReadBigEndianBytes(2), 0);
		}

		public int ReadInt32()
		{
			return BitConverter.ToInt32(ReadBigEndianBytes(4), 0);
		}

		public long ReadInt64()
		{
			return BitConverter.ToInt64(ReadBigEndianBytes(8), 0);
		}

		protected byte[] ReadBigEndianBytes(int count)
		{
			byte[] bytes = new byte[count];
			for (int c = bytes.Length - 1; c >= 0; c--)
				bytes[c] = m_Reader.ReadByte();
			return bytes;
		}

		public void Dispose()
		{
			if (m_DisposeInnerReader && m_Reader != null)
				m_Reader.Dispose();
			m_Reader = null;
		}
	}
}
